<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>浪起BI-ETL平台</title>
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome 图标库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #f8f9fa;
            height: 100vh;
            display: flex;
        }
        /* 确保没有额外的间隔 */
        #sidebar {
            margin: 0;
            padding: 0;
        }
        .content {
            flex: 1;
            padding: 20px;
            background: white;
            margin-left: 0;
            transition: margin-left 0.3s ease-in-out; /* 添加平滑过渡效果 */
        }
        .content.collapsed {
            margin-left: 60px; /* 当侧边栏收缩时，内容区域向左移动 */
        }
        /* 确保main和section元素之间没有额外的margin */
        main {
            margin: 0;
        }
        section {
            margin: 0;
        }
        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .table th, .table td {
            border: 1px solid #ccc;
            padding: 10px;
            text-align: left;
        }
        .table th {
            background: #f0f0f0;
        }
        footer {
            text-align: center;
            padding: 10px;
            background: white;
            box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>
    <!-- 公共导航栏 -->
    {% include 'sidebar.html' %}
    <main id="content" class="content">
        <section class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
            <div class="flex flex-col space-y-2">
                <label for="table-name" class="font-medium text-gray-700">数据表名称</label>
                <select id="table-name" class="border border-gray-300 rounded px-3 py-2 w-full focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">请选择数据表</option>
                </select>
            </div>
            <div class="flex flex-col space-y-2">
                <label for="platform" class="font-medium text-gray-700">平台</label>
                <select id="platform" class="border border-gray-300 rounded px-3 py-2 w-full focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">选择平台</option>
                </select>
            </div>
            <div class="flex flex-col space-y-2">
                <label for="store" class="font-medium text-gray-700">店铺</label>
                <select id="store" class="border border-gray-300 rounded px-3 py-2 w-full focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">选择店铺</option>
                </select>
            </div>
            <div class="flex flex-col space-y-2">
                <label for="operate-type" class="font-medium text-gray-700">导入规则</label>
                <select id="operate-type" class="border border-gray-300 rounded px-3 py-2 w-full focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">选择导入规则</option>
                </select>
            </div>
            <div class="flex flex-col space-y-2">
                <label class="font-medium text-gray-700">开始时间</label>
                <input type="date" id="start-date" class="border border-gray-300 rounded px-3 py-2 w-full focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="开始时间">
            </div>
            <div class="flex flex-col space-y-2">
                <label class="font-medium text-gray-700">结束时间</label>
                <input type="date" id="end-date" class="border border-gray-300 rounded px-3 py-2 w-full focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="结束时间">
            </div>
            <div class="flex flex-col space-y-2">
                <label for="run-flag" class="font-medium text-gray-700">运行状态</label>
                <select id="run-flag" class="border border-gray-300 rounded px-3 py-2 w-full focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">选择运行状态</option>
                </select>
            </div>
            <div class="flex flex-col space-y-2">
                <label for="remark-search" class="font-medium text-gray-700">备注</label>
                <input type="text" id="remark-search" class="border border-gray-300 rounded px-3 py-2 w-full focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="输入备注关键词进行模糊查询">
            </div>
            <div class="flex flex-col space-y-2 justify-end">
                <div class="flex items-end space-x-2">
                    <!-- 搜索和重置按钮已移到下方操作按钮区域 -->
                </div>
            </div>
        </section>
        <div class="flex flex-wrap gap-3 mb-8 items-center">
            <button onclick="searchTasks()" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">搜索</button>
            <button onclick="resetSearch()" class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600">重置</button>
            <button onclick="openImportModal()" class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600">创建任务</button>
            <button onclick="syncKingdee()" class="bg-purple-600 text-white px-4 py-2 rounded hover:bg-purple-700">同步金蝶</button>
            <button onclick="api_test()" class="bg-orange-500 text-white px-4 py-2 rounded hover:bg-orange-600">测试验证</button>
        </div>
        <section class="mt-6">
            <h2 class="text-lg font-bold"></h2>
            <table class="min-w-full bg-white border border-gray-200">
                <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                选择
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">序号</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数据表名称</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">平台</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">店铺</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">开始时间</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">结束时间</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">导入规则</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">运行状态</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">运行状态名称</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">运行时间</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">备注</th>
                        </tr>
                    </thead>
                    <tbody id="tblData">
                        <tr>
                            <td colspan="10" class="text-center py-8 text-gray-500">暂无数据</td>
                        </tr>
                    </tbody>
            </table>
            <!-- 分页控件 -->
            <div class="mt-4 flex justify-between items-center">
                <div class="text-sm text-gray-700">
                    共 <span id="totalRecords">0</span> 条记录
                </div>
                <div class="flex items-center space-x-2">
                    <button id="prevPage" onclick="changePage(-1)" class="px-3 py-1 border rounded text-sm disabled:opacity-50">上一页</button>
                    <select id="pageSelect" onchange="jumpToPage()" class="px-2 py-1 border rounded text-sm">
                         <option value="1">1</option>
                     </select>
                     <span class="text-sm text-gray-600">/ <span id="totalPages">1</span></span>
                    <button id="nextPage" onclick="changePage(1)" class="px-3 py-1 border rounded text-sm disabled:opacity-50">下一页</button>
                </div>
            </div>
        </section>
    </main>

    <style>
        /* 模态框样式补充 */
        .modal-enter {
            opacity: 0;
        }
        .modal-enter-active {
            opacity: 1;
            transition: opacity 300ms;
        }
        .modal-exit {
            opacity: 1;
        }
        .modal-exit-active {
            opacity: 0;
            transition: opacity 300ms;
        }
    </style>

    <script>
        const importButton = document.querySelector('.bg-green-500');
        const importModal = document.getElementById('importModal');
        const closeModal = document.getElementById('closeModal');
        const cancelImport = document.getElementById('cancelImport');

        // 加载平台和店铺数据
        async function loadPlatformsAndStores() {
            try {
                const response = await fetch('/api/platforms');
                const platformsData = await response.json();
                
                // 清空现有选项
                platformSelect.innerHTML = '<option value="">选择平台</option>';
                
                // 添加平台选项
                platformsData.forEach(platform => {
                    const option = document.createElement('option');
                    option.value = platform.plat_id;
                    option.textContent = platform.plat_name;
                    platformSelect.appendChild(option);
                });
                
                // 绑定平台变化事件
                platformSelect.addEventListener('change', handlePlatformChange);
                
            } catch (error) {
                console.error('加载平台数据失败:', error);
            }
        }

        // 处理平台选择变化
        async function handlePlatformChange(event) {
            const selectedPlatform = event.target.value;
            if (selectedPlatform && selectedPlatform !== '选择平台') {
                try {
                    // 获取平台详细信息
                    const platformsResponse = await fetch('/api/platforms');
                    const platforms = await platformsResponse.json();
                    const selectedPlatformInfo = platforms.find(p => p.plat_id === selectedPlatform);
                    
                    //弹窗提示信息
                    //if (selectedPlatformInfo) {
                    //    alert(`平台信息：\nID: ${platforms.indexOf(selectedPlatformInfo)}\n平台ID: ${selectedPlatformInfo.plat_id}\n平台名称: ${selectedPlatformInfo.plat_name}`);
                    //}
                    
                    const response = await fetch(`/api/stores/${encodeURIComponent(selectedPlatform)}`);
                    const stores = await response.json();
                    
                    // 清空并添加店铺选项
                    storeSelect.innerHTML = '<option value="">选择店铺</option>';
                    stores.forEach(store => {
                        const option = document.createElement('option');
                        option.value = store.shop_id;
                        option.textContent = store.shop_name;
                        storeSelect.appendChild(option);
                    });
                } catch (error) {
                    console.error('加载店铺数据失败:', error);
                }
            } else {
                storeSelect.innerHTML = '<option value="">选择店铺</option>';
            }
        }





        // 加载账套数据
        async function loadAccounts() {
            try {
                const response = await fetch('/api/accounts');
                const accounts = await response.json();
                
                const accountSelect = document.getElementById('account-select');
                accountSelect.innerHTML = '<option value="">请选择账套</option>';
                
                accounts.forEach(account => {
                    const option = document.createElement('option');
                    option.value = account.id;
                    option.textContent = account.name;
                    option.setAttribute('data-id', account.acctId);
                    accountSelect.appendChild(option);
                });
                
                // 绑定账套选择事件
                accountSelect.addEventListener('change', handleAccountChange);
                
            } catch (error) {
                console.error('加载账套数据失败:', error);
            }
        }

        // 加载导入规则数据
        async function loadOperateTypes() {
            try {
                const response = await fetch('/api/operate-types');
                const operateTypes = await response.json();
                
                const operateTypeSelect = document.getElementById('operate-type');
                operateTypeSelect.innerHTML = '<option value="">选择导入规则</option>';
                
                operateTypes.forEach(type => {
                    const option = document.createElement('option');
                    option.value = type.id;
                    option.textContent = type.name;
                    operateTypeSelect.appendChild(option);
                });
                
            } catch (error) {
                console.error('加载导入规则数据失败:', error);
            }
        }

        // 加载运行状态数据
        async function loadRunFlags() {
            try {
                // 运行状态映射
                const runFlags = [
                    {id: 10, name: '待处理'},
                    {id: 20, name: '处理中'},
                    {id: 30, name: '已完成'},
                    {id: 40, name: '失败'},
                    {id: 50, name: '已取消'}
                ];
                
                const runFlagSelect = document.getElementById('run-flag');
                runFlagSelect.innerHTML = '<option value="">选择运行状态</option>';
                
                runFlags.forEach(flag => {
                    const option = document.createElement('option');
                    option.value = flag.id;
                    option.textContent = flag.name;
                    runFlagSelect.appendChild(option);
                });
                
            } catch (error) {
                console.error('加载运行状态数据失败:', error);
            }
        }

        // 处理账套选择变化
        function handleAccountChange(event) {
            const selectedOption = event.target.selectedOptions[0];
            if (selectedOption && selectedOption.value) {
                const id = selectedOption.value;
                const name = selectedOption.textContent;
                alert(`账套信息：\nID: ${id}\n名称: ${name}`);
            }
        }

        // 加载数据表数据
        async function loadTableNames() {
            try {
                const response = await fetch('/api/tables');
                const tables = await response.json();
                
                const tableSelect = document.getElementById('table-name');
                
                tableSelect.innerHTML = '<option value="">请选择数据表</option>';
                
                tables.forEach(table => {
                    const option = document.createElement('option');
                    option.value = table.table_name;  // 使用实际表名作为value
                    option.textContent = table.name;  // 使用显示名称作为文本
                    tableSelect.appendChild(option);
                });
                
            } catch (error) {
                console.error('加载数据表数据失败:', error);
            }
        }

        // 加载任务数据
        let currentPage = 1;
        const pageSize = 10;

        async function loadTasks(page = 1) {
            try {
                // 清空选择状态
                clearSelection();
                
                const params = new URLSearchParams();
                params.append('page', page);
                params.append('page_size', pageSize);
                
                // 添加过滤条件
                const tableName = document.getElementById('table-name')?.value || '';
                const platform = document.getElementById('platform')?.value || '';
                const store = document.getElementById('store')?.value || '';
                const startDate = document.getElementById('start-date')?.value || '';
                const endDate = document.getElementById('end-date')?.value || '';
                const operateType = document.getElementById('operate-type')?.value || '';
                const runFlag = document.getElementById('run-flag')?.value || '';
                const runFlagName = document.getElementById('run-flag_name')?.value || '';
                const remarkSearch = document.getElementById('remark-search')?.value || '';
                
                if (tableName) params.append('table_name', tableName);
                if (platform) params.append('plat_id', platform);
                if (store) params.append('shop_id', store);
                if (startDate) params.append('start_time_start', startDate);
                if (endDate) params.append('start_time_end', endDate);
                if (operateType) params.append('operate_type', operateType);
                if (runFlag) params.append('run_flag', runFlag);
                if (runFlagName) params.append('run_flag_name', runFlagName);
                if (remarkSearch) params.append('remark_like', remarkSearch);
                const response = await fetch(`/api/tasks?${params.toString()}`);
                const result = await response.json();
                
                if (result.error) {
                    console.error('加载任务数据失败:', result.error);
                    return;
                }

                const tbody = document.getElementById('tblData');
                const totalRecords = document.getElementById('totalRecords');
                const prevBtn = document.getElementById('prevPage');
                const nextBtn = document.getElementById('nextPage');

                // 清空现有数据
                tbody.innerHTML = '';

                if (result.data && result.data.length > 0) {
                    result.data.forEach(task => {
                        const row = document.createElement('tr');
                        row.setAttribute('data-id', task.id);
                        row.innerHTML = `
                            <td class="px-6 py-4 whitespace-nowrap">
                                <input type="checkbox" name="task-select" class="row-checkbox form-checkbox h-4 w-4 text-blue-600 border-gray-300 focus:ring-blue-500" value="${task.id}">
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${task.id}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${task.tablename || '-'}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${task.plat_name || '-'}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${task.shop_name || '-'}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${task.starttime || '-'}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${task.endtime || '-'}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${task.operate_type || '-'}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${task.run_flag || '-'}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${task.run_flag_name || '-'}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${task.last_run_time || '-'}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${task.remark || '-'}</td>
                        `;
                        tbody.appendChild(row);
                    });
                    
                    // 绑定复选框事件（实现单选功能）
                 bindCheckboxEvents();
                } else {
                    tbody.innerHTML = '<tr><td colspan="11" class="text-center py-8 text-gray-500">暂无数据</td></tr>';
                }

                // 更新分页信息
                totalRecords.textContent = result.total || 0;
                const totalPages = result.total_pages || 1;
                
                // 更新页码选择器
                const pageSelect = document.getElementById('pageSelect');
                const totalPagesSpan = document.getElementById('totalPages');
                
                pageSelect.innerHTML = '';
                 for (let i = 1; i <= totalPages; i++) {
                     const option = document.createElement('option');
                     option.value = i;
                     option.textContent = i;
                     option.selected = i === page;
                     pageSelect.appendChild(option);
                 }
                
                totalPagesSpan.textContent = totalPages;
                
                // 更新分页按钮状态
                prevBtn.disabled = page <= 1;
                nextBtn.disabled = page >= totalPages;
                
                currentPage = page;

            } catch (error) {
                console.error('加载任务数据失败:', error);
            }
        }

        // 切换分页
        function changePage(direction) {
            const newPage = currentPage + direction;
            const totalPagesElement = document.getElementById('totalPages');
            const totalPages = totalPagesElement ? parseInt(totalPagesElement.textContent) || 1 : 1;
            if (newPage >= 1 && newPage <= totalPages) {
                currentPage = newPage;
                loadTasks(currentPage);
            }
        }

        // 跳转到指定页
        function jumpToPage() {
            const pageSelect = document.getElementById('pageSelect');
            if (pageSelect && pageSelect.value) {
                const selectedPage = parseInt(pageSelect.value);
                if (selectedPage >= 1) {
                    currentPage = selectedPage;
                    loadTasks(currentPage);
                }
            }
        }

        // 单选功能
        let selectedRowId = null;

        // 绑定复选框事件（实现单选功能）
        function bindCheckboxEvents() {
            document.querySelectorAll('.row-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    if (this.checked) {
                        // 取消其他复选框的选中状态
                        document.querySelectorAll('.row-checkbox').forEach(cb => {
                            if (cb !== this) {
                                cb.checked = false;
                            }
                        });
                        selectedRowId = this.value;
                    } else {
                        // 如果取消选中，则清空selectedRowId
                        selectedRowId = null;
                    }
                });
            });
        }

        // 获取选中的记录ID
        function getSelectedIds() {
            return selectedRowId ? [selectedRowId] : [];
        }

        // 获取选中的单个记录ID
        function getSelectedId() {
            return selectedRowId;
        }

        // 清空选择
        function clearSelection() {
            selectedRowId = null;
            document.querySelectorAll('.row-checkbox:checked').forEach(checkbox => {
                checkbox.checked = false;
            });
        }

        // 同步金蝶处理函数
        function syncKingdee() {
            const selectedId = getSelectedId();
            
            if (!selectedId) {
                alert('请选择要同步的记录！');
                return;
            }
            
            // 调用后端API同步金蝶
            fetch('/api/sync-kingdee', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    task_id: selectedId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    // 重新加载任务列表以更新状态
                    loadTasks();
                } else {
                    alert('同步失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('同步金蝶错误:', error);
                alert('同步失败：网络错误');
            });
        }

        // 搜索任务
        function searchTasks() {
            currentPage = 1;
            loadTasks(currentPage);
        }

        // 重置搜索条件
        function resetSearch() {
            const tableNameElement = document.getElementById('table-name');
            if (tableNameElement) tableNameElement.value = '';
            
            const platformElement = document.getElementById('platform');
            if (platformElement) platformElement.value = '';
            
            const storeElement = document.getElementById('store');
            if (storeElement) storeElement.value = '';
            
            const startDateElement = document.getElementById('start-date');
            if (startDateElement) startDateElement.value = '';
            
            const endDateElement = document.getElementById('end-date');
            if (endDateElement) endDateElement.value = '';
            
            const operateTypeElement = document.getElementById('operate-type');
            if (operateTypeElement) operateTypeElement.value = '';
            
            const runFlagElement = document.getElementById('run-flag');
            if (runFlagElement) runFlagElement.value = '';
            
            const remarkSearchElement = document.getElementById('remark-search');
            if (remarkSearchElement) remarkSearchElement.value = '';
            
            currentPage = 1;
            loadTasks(currentPage);
        }

        // 页面加载时初始化数据
        document.addEventListener('DOMContentLoaded', () => {
            // 获取DOM元素
            const platformSelect = document.getElementById('platform');
            const storeSelect = document.getElementById('store');
            
            // 定义加载平台和店铺数据的函数
            async function loadPlatformsAndStores() {
                try {
                    const response = await fetch('/api/platforms');
                    const platformsData = await response.json();
                    
                    // 清空现有选项
                    if (platformSelect) {
                        platformSelect.innerHTML = '<option value="">选择平台</option>';
                        
                        // 添加平台选项
                        platformsData.forEach(platform => {
                            const option = document.createElement('option');
                            option.value = platform.plat_id;
                            option.textContent = platform.plat_name;
                            platformSelect.appendChild(option);
                        });
                        
                        // 绑定平台变化事件
                        platformSelect.addEventListener('change', async function(event) {
                            const selectedPlatform = event.target.value;
                            if (selectedPlatform && selectedPlatform !== '选择平台') {
                                try {
                                    // 获取平台详细信息
                                    const platformsResponse = await fetch('/api/platforms');
                                    const platforms = await platformsResponse.json();
                                    const selectedPlatformInfo = platforms.find(p => p.plat_id === selectedPlatform);
                                    
                                    const response = await fetch(`/api/stores/${encodeURIComponent(selectedPlatform)}`);
                                    const stores = await response.json();
                                    
                                    // 清空并添加店铺选项
                                    if (storeSelect) {
                                        storeSelect.innerHTML = '<option value="">选择店铺</option>';
                                        stores.forEach(store => {
                                            const option = document.createElement('option');
                                            option.value = store.shop_id;
                                            option.textContent = store.shop_name;
                                            storeSelect.appendChild(option);
                                        });
                                    }
                                } catch (error) {
                                    console.error('加载店铺数据失败:', error);
                                }
                            } else if (storeSelect) {
                                storeSelect.innerHTML = '<option value="">选择店铺</option>';
                            }
                        });
                    }
                } catch (error) {
                    console.error('加载平台数据失败:', error);
                }
            }
            
            // 初始化数据加载
            loadPlatformsAndStores();
            loadAccounts();
            loadTableNames();
            loadOperateTypes();
            loadRunFlags();
            loadTasks();
            
            // 设置3秒定时自动刷新数据
            let refreshInterval = setInterval(() => {
                // 保存当前选中的记录ID
                const selectedId = getSelectedId();
                loadTasks(currentPage).then(() => {
                    // 恢复选中状态
                    if (selectedId) {
                        const checkbox = document.querySelector(`.row-checkbox[value="${selectedId}"]`);
                        if (checkbox) {
                            checkbox.checked = true;
                            selectedRowId = selectedId;
                        }
                    }
                });
            }, 3000);
            
            // 提供暂停/继续自动刷新的功能
            window.pauseAutoRefresh = function() {
                if (refreshInterval) {
                    clearInterval(refreshInterval);
                    refreshInterval = null;
                    console.log('自动刷新已暂停');
                }
            };
            
            window.resumeAutoRefresh = function() {
                if (!refreshInterval) {
                    refreshInterval = setInterval(() => {
                        // 保存当前选中的记录ID
                        const selectedId = getSelectedId();
                        loadTasks(currentPage).then(() => {
                            // 恢复选中状态
                            if (selectedId) {
                                const checkbox = document.querySelector(`.row-checkbox[value="${selectedId}"]`);
                                if (checkbox) {
                                    checkbox.checked = true;
                                    selectedRowId = selectedId;
                                }
                            }
                        });
                    }, 3000);
                    console.log('自动刷新已恢复');
                }
            };
        });

        // 测试验证函数
        function api_test() {
            const currentTime = new Date().toISOString();
            console.log('测试验证开始，当前时间:', currentTime);
            
            // 显示加载状态
            const testBtn = event.target;
            const originalText = testBtn.textContent;
            testBtn.textContent = '验证中...';
            testBtn.disabled = true;
            
            // 调用测试API
            fetch('/api/test', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    timestamp: currentTime,
                    message: '测试验证请求'
                })
            })
            .then(response => response.json())
            .then(data => {
                console.log('测试验证结果:', data);
                if (data.success) {
                    alert('测试验证成功！\n时间: ' + currentTime + '\n响应: ' + (data.message || 'OK'));
                } else {
                    alert('测试验证失败：' + (data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('测试验证错误:', error);
                alert('测试验证失败：网络错误');
            })
            .finally(() => {
                // 恢复按钮状态
                testBtn.textContent = originalText;
                testBtn.disabled = false;
            });
        }
    </script>
    <!-- 导入模态弹窗 -->
    <div id="importModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-4xl h-5/6 max-h-screen relative">
            <!-- 关闭按钮 -->
            <button onclick="closeImportModal()" class="absolute top-4 right-4 text-gray-500 hover:text-gray-700 z-10">
                <i class="fas fa-times text-xl"></i>
            </button>
            
            <!-- 模态内容 -->
            <div class="h-full">
                <iframe id="importFrame" src="/import-modal.html" class="w-full h-full rounded-lg" frameborder="0"></iframe>
            </div>
        </div>
    </div>

    <script>
        // 打开导入模态弹窗
        function openImportModal() {
            // 检查是否已选择账套
            const accountSelect = document.getElementById('account-select');
            if (!accountSelect || !accountSelect.value) {
                alert('请先选择账套！');
                return;
            }
            
            const modal = document.getElementById('importModal');
            const frame = document.getElementById('importFrame');
            
            // 设置iframe源并显示模态框
            frame.src = '/import-modal.html';
            modal.classList.remove('hidden');
        }

        // 关闭导入模态弹窗
        function closeImportModal() {
            const modal = document.getElementById('importModal');
            const frame = document.getElementById('importFrame');
            
            // 隐藏模态框并重置iframe
            modal.classList.add('hidden');
            frame.src = '';
        }

        // 点击模态框背景关闭
        document.getElementById('importModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeImportModal();
            }
        });

        // ESC键关闭模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                const modal = document.getElementById('importModal');
                if (!modal.classList.contains('hidden')) {
                    closeImportModal();
                }
            }
        });
    </script>
</body>
</html>